package com.balabala.gym_system.service.impl;

import com.balabala.api.UserVipCardFeignClient;
import com.balabala.exception.CustomerException;
import com.balabala.goods.api.CourseFeignClient;
import com.balabala.goods.pojo.vo.BookCourseDto;
import com.balabala.goods.pojo.vo.CourseDto;
import com.balabala.gym_enum.ExceptionEnum;
import com.balabala.gym_system.mapper.AdminMapper;
import com.balabala.gym_system.mapper.CoachMapper;
import com.balabala.gym_system.mapper.ReservationInfoMapper;
import com.balabala.gym_system.pojo.dto.ReservationInfoQueryDto;
import com.balabala.gym_system.pojo.dto.ReservationListDto;
import com.balabala.gym_system.pojo.entity.ReservationInfo;
import com.balabala.gym_system.pojo.vo.AdminVo;
import com.balabala.gym_system.pojo.vo.CoachVo;
import com.balabala.gym_system.pojo.vo.CourseInfoVo;
import com.balabala.gym_system.pojo.vo.ReservationInfoVo;
import com.balabala.gym_system.service.ReservationInfoService;
import com.balabala.result.Result;
import com.balabala.vo.UserVipCardInfoVO;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.time.DateFormatUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class ReservationInfoServiceImpl extends ServiceImpl<ReservationInfoMapper,ReservationInfo> implements ReservationInfoService {

    @Autowired
    //远程调用vip接口
    private UserVipCardFeignClient userVipCardFeignClient;

    @Autowired
    //远程调用预约课程和记录信息
    private CourseFeignClient courseFeignClient;

    @Autowired
    //查询教练表
    private CoachMapper coachMapper;

    @Autowired
    //查询教练表
    private AdminMapper adminMapper;

    @Override
    public List<ReservationInfo> findAll() {

        //查询全部
        return this.list();
    }

    //
    @Override
    public List<ReservationInfoVo> findList(ReservationInfoQueryDto reservationInfoQueryDto) {

        /*// 1组装分页条件
        PageHelper.startPage(reservationInfoQueryDto.getPage(),reservationInfoQueryDto.getLimit());
        List<ReservationInfo> list = this.list();

        //获取分页信息
        PageInfo<ReservationInfo> info = new PageInfo<>(list);*/
        //查询全部
        List<ReservationInfo> list = this.findAll();

        List<ReservationInfoVo> reservationInfoVoList=new ArrayList<>();

        list.forEach(r->{

            log.info("vipId:{}",r.getVuId());
            //远程调用查询会员信息
            Result<UserVipCardInfoVO> userCardInfo = userVipCardFeignClient.getUserCardInfo(r.getVuId());
            log.info("getVuId=======:{}",r.getVuId());
            //新建vo 依次拷贝
            ReservationInfoVo reservationInfoVo=new ReservationInfoVo();
            BeanUtils.copyProperties(r,reservationInfoVo);

            //设置会员卡名称
            reservationInfoVo.setVipName(userCardInfo.getData().getCardName());

            //设置会员卡备注
            reservationInfoVo.setRemark(userCardInfo.getData().getRemark());

            //设置会员名称
            reservationInfoVo.setName(userCardInfo.getData().getUsername());

            //设置会员电话号码
            reservationInfoVo.setPhone(userCardInfo.getData().getPhone());

            //添加reservationInfoVo到 reservationInfoVoList
            reservationInfoVoList.add(reservationInfoVo);

        });

        return reservationInfoVoList;
    }

    //添加预约记录
    @Override
    @Transactional
    public void addReservationInfo(ReservationInfo reservationInfo) {

        //远程调用预约课程和记录信息
        //根据排课id查询排课信息 判断是否到达预约上限
        Result<BookCourseDto> byScheduleId = courseFeignClient.findByScheduleId(reservationInfo.getBookId());

        //判断人数是否合理
         if (byScheduleId.getData().getClassOrderNumber()<(byScheduleId.getData().getNumAppointment()+reservationInfo.getBookingNum())){

             //超出人数上限
             log.error("超出人数上限:{}",reservationInfo.getBookingNum());
             throw new CustomerException(ExceptionEnum.MORE_THAN_PEOPLE);
         }
             //人数合理 直接插入
             getBaseMapper().insert(reservationInfo);

             //根据id查询课程信息（已预约人数）
        Result<CourseDto> courseById = courseFeignClient.getCourseById(reservationInfo.getCourseId());
        //获取data数据
        CourseDto courseDto = courseById.getData();

        //修改已经预约人数
        courseDto.setNumAppointment(courseDto.getNumAppointment()+reservationInfo.getBookingNum());


        //设置改变的预约人数到数据库
        courseFeignClient.update(courseDto);

    }

    //根据id删除预约记录
    @Override
    @Transactional //事物注解
    public void deleteById(Long id) {

        //根据id查询预约记录表信息
        ReservationInfo reservationInfo = getBaseMapper().selectById(id);

        // 获取要删除的预约记录表的预约人数
        Integer bookingNum = reservationInfo.getBookingNum();

        //根据id查询课程信息
        Result<CourseDto> courseById = courseFeignClient.getCourseById(reservationInfo.getCourseId());

        CourseDto data = courseById.getData();
        //将已经预约人数更新
        data.setNumAppointment(data.getNumAppointment()-bookingNum);

        //更新预约人数到数据库
        courseFeignClient.update(data);

        getBaseMapper().deleteById(id);
    }

    //根据id签到
    @Override
    public void updateStatusById(Long id) {
        ReservationInfo reservationInfo = getBaseMapper().selectById(id);
        //将状态改为1
        reservationInfo.setStatus(1);
        getBaseMapper().updateById(reservationInfo);
    }


    //根据排课id查询排课预约记录
    @Override
    public List<ReservationInfoVo> findListByBookId(Long id) {

        List<ReservationInfo> list = getBaseMapper().findListByBookId(id);

        List<ReservationInfoVo> reservationInfoVoList=new ArrayList<>();

        list.forEach(r->{

            log.info("vipId:{}",r.getVuId());
            //远程调用查询会员信息
            Result<UserVipCardInfoVO> userCardInfo = userVipCardFeignClient.getUserCardInfo(r.getVuId());
            log.info("getVuId=======:{}",r.getVuId());
            //新建vo 依次拷贝
            ReservationInfoVo reservationInfoVo=new ReservationInfoVo();
            BeanUtils.copyProperties(r,reservationInfoVo);

            //设置预约时间格式
            String str= DateFormatUtils.format(r.getCreateTime(), "yyyy-MM-dd HH:mm:SS");
            String[] split = str.split(":");
            String str1 = split[0]+":"+split[1];

            reservationInfoVo.setCreateTime(str1);

            //设置会员卡名称
            reservationInfoVo.setVipName(userCardInfo.getData().getCardName());

            //设置会员卡备注
            reservationInfoVo.setRemark(userCardInfo.getData().getRemark());

            //设置会员名称
            reservationInfoVo.setName(userCardInfo.getData().getUsername());

            //设置会员电话号码
            reservationInfoVo.setPhone(userCardInfo.getData().getPhone());

            //添加reservationInfoVo到 reservationInfoVoList
            reservationInfoVoList.add(reservationInfoVo);

        });

        return reservationInfoVoList;
    }

    //根据排课id查询排课详情信息
    @Override
    public CourseInfoVo findByScheduleId(@RequestParam  Long scheduleId) {
        BookCourseDto data = courseFeignClient.findByScheduleId(scheduleId).getData();

        //拷贝数据
        CourseInfoVo courseInfoVo=new CourseInfoVo();
        BeanUtils.copyProperties(data,courseInfoVo);

        //根据教练id查询教练名称
        CoachVo byCoachId = coachMapper.findById(data.getCoachId());

        //根据教练表中的用户id查询用户名称
        AdminVo byAdminId = adminMapper.findById(byCoachId.getAdminId());

        //设置教练名称
        courseInfoVo.setCoachName(byAdminId.getName());

        //设置Vo的上课的时间区间 9:00-10:00
        String str= DateFormatUtils.format(data.getStartTime(), "yyyy-MM-dd HH:mm:SS");
        String[] split = str.split(":");
        String str1 = split[0]+":"+split[1];
        String end = DateFormatUtils.format(data.getEndTime(), "yyyy-MM-dd HH:mm:SS");
        String[] time = end.split(" ");
        String time1 = time[1];
        String[] time2 = time1.split(":");
        String time3=time2[0]+":"+time2[1];
        String time4=str1+"至"+time3;

        courseInfoVo.setDateRange(time4);

        //根据课程id查询课程信息
        Result<CourseDto> courseById = courseFeignClient.getCourseById(data.getCourseId());
        //得到已预约人数
        courseInfoVo.setNumAppointment(courseById.getData().getNumAppointment());



        return courseInfoVo;
    }
}
